//
//  CompleteViewController.swift
//  BusinessIOS
//
//  Created by Rain on 2018/11/5.
//  Copyright © 2018 XingJian Li. All rights reserved.
//

import UIKit
import Alamofire
class CompleteViewController: UIViewController {
    var tableView: UITableView!
    var CompleteArrays = [CompleteModel]()
    
    
    var bigCompleteArrays = [CompleteModel]()
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var index = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = bgGrayColor;
        navigationItem.title="我的待办"
        
        tableView = UITableView(frame:self.view.frame, style:.plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false

        tableView.tableFooterView = UIView.init()
        
        
        tableView.register(NSClassFromString("ContentTableViewCell"), forCellReuseIdentifier: "ContentCell")
        
        
        view.addSubview(tableView)
        tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        // Do any additional setup after loading the view.
//        self.taskData()
        
        
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        // 现在的版本要用mj_header
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
        
    }
    @objc func headerRefresh(){
        self.CompleteArrays.removeAll()
        self.bigCompleteArrays.removeAll()
        
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getMyTask"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(1)\",\"pageSize\":\"\(5)\"}"
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {
            (response) in
            
            print("1111===\(response)")
            if response.result.isSuccess {
                
                
                let json = JSON(response.data!)
                
                let array  = json["resultData"].array;
                
                for dataDic in  array!
                {
                    let model =   CompleteModel()
                    
                    model.createTime = dataDic["createTime"].string
                    model.departmentName = dataDic["departmentName"].string
                    model.deploymentName = dataDic["deploymentName"].string
                    model.informationRecordId = dataDic["informationRecordId"].string
                    model.projectIsExcute = dataDic["projectIsExcute"].string
                    model.projectName = dataDic["projectName"].string
                    
                    model.projectNum = dataDic["projectNum"].string
                    model.projectStage = dataDic["projectStage"].string
                    model.questionDesp = dataDic["questionDesp"].string
                    model.questionLevel = dataDic["questionLevel"].string
                    model.taskId = dataDic["taskId"].string
                    model.taskName = dataDic["taskName"].string
                    self.CompleteArrays.append(model)
                    
                }
                self.bigCompleteArrays.append(contentsOf: self.CompleteArrays)
                
                
                self.tableView.reloadData()
                
                self.tableView.mj_header.endRefreshing()
                
            }else{
                self.tableView.mj_header.endRefreshing()
            }
          
            
        }
        
    }
    
    @objc func footerRefresh(){
        self.CompleteArrays.removeAll()
        
        index += 1
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getMyTask"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(index)\",\"pageSize\":\"\(5)\"}"
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {
            (response) in
            
            print("1111===\(response)")
            if response.result.isSuccess {
                
                
                let json = JSON(response.data!)
                
                let array  = json["resultData"].array;
                
                for dataDic in  array!
                {
                    let model =   CompleteModel()
                    
                    model.createTime = dataDic["createTime"].string
                    model.departmentName = dataDic["departmentName"].string
                    model.deploymentName = dataDic["deploymentName"].string
                    model.informationRecordId = dataDic["informationRecordId"].string
                    model.projectIsExcute = dataDic["projectIsExcute"].string
                    model.projectName = dataDic["projectName"].string
                    
                    model.projectNum = dataDic["projectNum"].string
                    model.projectStage = dataDic["projectStage"].string
                    model.questionDesp = dataDic["questionDesp"].string
                    model.questionLevel = dataDic["questionLevel"].string
                    model.taskId = dataDic["taskId"].string
                    model.taskName = dataDic["taskName"].string
                    self.CompleteArrays.append(model)
                    
                }
                self.bigCompleteArrays.append(contentsOf: self.CompleteArrays)
                
                
                self.tableView.reloadData()
                
                self.tableView.mj_footer.endRefreshing()
                
            }else{
                self.tableView.mj_footer.endRefreshing()
            }
            
            
        }
        
        
    }
    //我的待办
    func taskData(){
        
        
        let start:String? = "1"
        let pageSize:String? = "5"
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getMyTask"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(start!)\",\"pageSize\":\"\(pageSize!)\"}"
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {
            (response) in
            
            print("1111===\(response)")
            if response.result.isSuccess {
                
                
                let json = JSON(response.data!)
                
                let array  = json["resultData"].array;
                
                for dataDic in  array!
                {
                    let model =   CompleteModel()
                    
                    model.createTime = dataDic["createTime"].string
                    model.departmentName = dataDic["departmentName"].string
                    model.deploymentName = dataDic["deploymentName"].string
                    model.informationRecordId = dataDic["informationRecordId"].string
                    model.projectIsExcute = dataDic["projectIsExcute"].string
                    model.projectName = dataDic["projectName"].string
                    
                    model.projectNum = dataDic["projectNum"].string
                    model.projectStage = dataDic["projectStage"].string
                    model.questionDesp = dataDic["questionDesp"].string
                    model.questionLevel = dataDic["questionLevel"].string
                    model.taskId = dataDic["taskId"].string
                    model.taskName = dataDic["taskName"].string
                    self.CompleteArrays.append(model)
                    
                }
                
                
            }
            self.tableView.reloadData()
            
        }
        
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension CompleteViewController: UITableViewDelegate, UITableViewDataSource {
    
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.bigCompleteArrays.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 160
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = ContentTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "ContentCell")
        let cellModel:CompleteModel = self.bigCompleteArrays[indexPath.row]
        cell.ConversationingWithModel(model: cellModel)
        
        
//        button.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside)
        
        cell.StateButton.addTarget(self, action: #selector(StateButtonClick(button:)), for: .touchUpInside)
        
        cell.PassButton.addTarget(self, action: #selector(PassButtonClick(button:)), for: .touchUpInside)
        cell.selectionStyle = .none
        return cell
    }
    
    //办理
    @objc func StateButtonClick(button: UIButton)  {
        
        let cell1 = button.superview?.superview as! ContentTableViewCell
        let cellIndex = tableView.indexPath(for: cell1)
       
        
        let cellModel:CompleteModel = self.bigCompleteArrays[(cellIndex?.row)!]
        
        
        let XiangMuLuRuBanliVC =  XiangMuLuRuBanliViewController()
        XiangMuLuRuBanliVC.numIdString = cellModel.taskId
        XiangMuLuRuBanliVC.informationRecordId = cellModel.informationRecordId
        XiangMuLuRuBanliVC.deploymentName = cellModel.deploymentName
        
        XiangMuLuRuBanliVC.taskId = cellModel.taskId
        self.navigationController?.pushViewController(XiangMuLuRuBanliVC , animated: true)
        
        
    }
    
    //进度查询
    @objc func PassButtonClick(button: UIButton)  {
        let cell1 = button.superview?.superview as! ContentTableViewCell
        let cellIndex = tableView.indexPath(for: cell1)
        
        
        let cellModel:CompleteModel = self.bigCompleteArrays[(cellIndex?.row)!]
        
        let LookAlreadyTaskVC =  LookAlreadyTaskViewController()
        LookAlreadyTaskVC.numIdString = cellModel.informationRecordId
        self.navigationController?.pushViewController(LookAlreadyTaskVC , animated: true)
        
    }
    
    
    
}
